<template>
  <el-card class="local">
    <el-form ref="formData" :inline="true" :model="formData" label-width="120px" size="small">
      <el-col>
        <el-form-item prop="companyCode" label="单位名称：">
          <el-select v-model="formData.companyCode" placeholder="请选择单位" @change="companyChange" clearable style="width:250px;">
            <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="stationCode" label="场站名称：">
          <el-select v-model="formData.stationCode" placeholder="请选择场站" @change="stationChange" clearable style="width:250px;">
            <el-option v-for="item in stationList" :label="item.stationName" :value="item.stationCode"
                       :key="item.stationCode"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
<!--      <el-col>-->
<!--        <el-form-item :rules="{ required: true, message: '请选择任务编号', trigger: 'change'}" prop="inspectTaskCode"-->
<!--                      label="任务编号：">-->
<!--          <el-select v-model="formData.inspectTaskCode" placeholder="请选择任务" style="width:250px;">-->
<!--            <el-option v-for="item in taskNumberList" :label="item" :value="item"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-col>-->
      <el-col>
        <el-form-item :rules="{ required: true, message: '请选择数据', trigger: 'change'}" prop="filename" label="选择数据：">
          <el-upload style="width:250px;"
                     ref="upload"
                     class="upload-demo"
                     :show-file-list="false"
                     :on-change="fileChange"
                     action=""
                     multiple
                     :auto-upload="false">
            <el-input style="width:250px;" prefix-icon="el-icon-folder-add" placeholder="请选择数据"
                      v-model="formData.filename"></el-input>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item prop="name" label="备注：">
          <el-input type="textarea" style="width:635px;" v-model="formData.remark"></el-input>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item prop="type" label="选择方式：">
          <el-radio-group v-model="formData.type" @change="$refs.formData.clearValidate('title')">
            <el-radio :label="1">上传数据并启动智能诊断</el-radio>
            <el-radio :label="0">仅上传数据</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label="诊断模型：" prop="checkedMap">
          <div style="width:calc(83.333333vw - 250px); max-height:400px; overflow-y:auto;border:1px solid rgba(229,229,229,1);border-radius:4px; padding:0 10px;">
            <el-checkbox :disabled="formData.type !== 1" label="全选" @change="handleCheckAllChange" v-model="checkAll">全选</el-checkbox>
            <el-checkbox :disabled="formData.type !== 1" v-for="item in outerModelList" :key="item.id" :label="item.diagModelCode" @change="event => itemChange(event, item.diagModelCode)" v-model="checkedMap[item.diagModelCode]">
              <el-popover
                placement="top-start"
                width="200"
                trigger="hover"
                :content="item.remark">
                <span slot="reference">
                  {{ item.diagModelName }}
                </span>
              </el-popover>
            </el-checkbox>
          </div>
<!--          <el-checkbox :disabled="formData.type === 0" v-if="outerModelList.length > 1" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="display: inline-block; margin-right:10px; vertical-align:top;">全选</el-checkbox>-->
<!--          <el-checkbox-group :disabled="formData.type === 0" v-model="formData.title" style="display: inline-block;" @change="handleChange">-->
<!--            <div v-for="item in outerModelList" >-->
<!--              <el-checkbox :key="item.id" :label="item.diagModelCode">-->
<!--                <el-popover-->
<!--                  placement="top-start"-->
<!--                  width="200"-->
<!--                  trigger="hover"-->
<!--                  :content="item.remark">-->
<!--                  <span slot="reference">{{ item.diagModelName }}</span>-->
<!--                </el-popover>-->
<!--              </el-checkbox>-->
<!--            </div>-->
<!--          </el-checkbox-group>-->
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item label=" ">
          <el-button type="primary" @click="submitUpload" style="margin-top: 10px">开始上传</el-button>
        </el-form-item>
      </el-col>

    </el-form>
  </el-card>
</template>

<script>
  import eventBus from "../../../eventBus"
  import stations from "../../../api/stations"
  import manual from "../../../api/manual"
  import dataSourceApi from "../../../api/dataSourceApi";

  export default {
    name: "local",
    data() {
      return {
        formData: {
          companyCode: "",
          stationCode: "",
          remark: "",
          title: [],
          inspectTaskCode: "",
          filename: "",
          type: 1
        },
        tree: [],
        checkedMap: {},
        checkAll: '',
        stationList: [],
        outerModelList: [],
        isIndeterminate: false,
        taskNumberList: []
      }
    },
    mounted() {
      this.getCompanyList()
      this.getOuterModelList()
    },
    methods: {
      submitUpload() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            // 校验文件是否上传过，未上传过才允许上传
            let titleArr = []
            for (let key in this.checkedMap) {
              if (this.checkedMap[key]) {
                titleArr.push(key)
              }
            }
            if (this.formData.type === 1 && titleArr.length < 1) {
              this.$message.error('请选择任务模型')
              return
            }
            if (this.formData.type === 1) {
              this.formData.diagModelCode = titleArr.join(',')
              this.formData.title = titleArr.join(',')
            }
            // console.log("this.formData", this.formData)
            this.formData.oriFileName = this.$refs.upload.uploadFiles[this.$refs.upload.uploadFiles.length - 1].name
            // dataSourceApi.getOriFileNameInfo({inspectTaskCode: this.formData.inspectTaskCode, oriFileName: this.formData.oriFileName}).then(res => {
            //   if (res && res.data.code === 200 && res.data.data.code === "1") {
            //     this.$message.error(res.data.data.message)
            //   } else {
            // 生成任务编号
            dataSourceApi.insertTaskInfo().then(res => {
              if (res && res.data.code === 200) {
                this.formData.inspectTaskCode = res.data.data.inspectTaskCode
                eventBus.$emit("uploadTask", {
                  blob: this.$refs.upload.uploadFiles[this.$refs.upload.uploadFiles.length - 1],
                  params: this.formData
                })
                this.$alert(`<strong style="color: #3977f3">生成任务编号：${this.formData.inspectTaskCode}</strong><br/><span>跳转至资源查询页面查看任务</span>`, '提示', {
                  dangerouslyUseHTMLString: true,
                  type: 'warning',
                  center: true,
                  callback: action => {
                    this.$router.push("/dataSource/dataSourceList")
                  }
                });
              }
            }).catch(e => {
                this.$message.error({message: e.message ? e.message : e, center: true})
            })
            //   }
            // }).catch(e => {
            //     this.$message.error({message: e.message ? e.message : e, center: true})
            // })
          }
        })
      },
      handleCheckAllChange(val) {
        for (let key in this.checkedMap) {
          this.checkedMap[key] = val
        }
      },
      itemChange(value, target) {
        if (value) {
          this.$set(this.checkedMap, [target], true)
          let i = 0
          for (let key in this.checkedMap) {
            if (this.checkedMap[key]) {
              i++
            }
          }
          if (i === this.outerModelList.length) {
            this.checkAll = true
          }
        } else {
          this.$set(this.checkedMap, [target], false)
          this.checkAll = false
        }
        this.$forceUpdate()
      },
      getCompanyList() {
        stations.getCompanyList().then(res => {
          if (res && res.data.code === 200) {
            this.tree = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      stationChange() {
        this.getTaskNumberByCompany()
        this.formData.inspectTaskCode = ""
      },
      companyChange() {
        this.formData.stationCode = ""
        this.formData.inspectTaskCode = ""
        this.getStationByCompany()
      },
      getTaskNumberByCompany() {
        manual.getTaskNumberByCompany1({
          companyCode: this.formData.companyCode,
          stationCode: this.formData.stationCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.taskNumberList = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      getStationByCompany() {
        manual.getStationByCompany({
          companyCode: this.formData.companyCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.stationList = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      fileChange(file) {
        const isZip = file.name.split(".")[file.name.split(".").length - 1] === "zip"
        const isRar= file.name.split(".")[file.name.split(".").length - 1] === "rar"
        if (!isZip && !isRar) {
          this.$message.error('只能上传ZIP或RAR格式文件!');
          return
        }
        this.formData.filename = file.name
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isZip || !isRar) {
        //   this.$message.error('只能上传ZIP或RAR格式文件!');
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        //   this.fileList = []
        // }
        return isJPG && isLt2M;
      },
      handleChange(value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === 3
        this.isIndeterminate = checkedCount > 0 && checkedCount < 3
      },
      getOuterModelList() {
        manual.getOuterModelList().then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.outerModelList = res.data.data
            this.outerModelList.map(item => {
              this.checkedMap[item.diagModelCode] = false
            })
          }
        })
      },
    }
  }
</script>

<style lang="scss">
  .local {
    .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner{
      background-color: #3977F3;
    }
    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
      margin-bottom: 15px;
    }
    .el-form-item{
      height: auto;
    }
    .el-card__body{
      min-height: calc(100vh - 159px);
    }
  }
</style>
